package com.tedu.springboot22102.controller;

import com.tedu.springboot22102.entity.Article;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

@Controller
public class ArticleController {
    private static File ArticleDir;

    static {
        ArticleDir = new File("./Article");
        if (!ArticleDir.exists()){
            ArticleDir.mkdir();
        }
    }

    @RequestMapping("/Article")
    public void Article(HttpServletRequest request, HttpServletResponse response){
        System.out.println("处理文章信息");

        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String neirong = request.getParameter("neirong");
        System.out.println("文章名："+title+" "+"作者名:"+author+" "+"内容:"+neirong);
        if (title==null||title.trim().isEmpty()||
            author==null||author.trim().isEmpty()||
                neirong==null||neirong.trim().isEmpty()
        ){
            try {
                response.sendRedirect("/Article_name_err");
                return;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


        Article article = new Article(title,author);
        File file = new File(ArticleDir,title+".obj");
        if (file.exists()){
            try {
                response.sendRedirect("Article_err.html");
                return;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        try(FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);) {
            oos.writeObject(article);
            response.sendRedirect("/Article_success.html");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


}
